package map;

import android.content.Context;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Created by 佳星 on 08-09-0009.
 */
public class MapWidget extends FrameLayout{
    public final View view;
    public final PointF position = new PointF();
    private RenderDelegate renderDelegate;

    public MapWidget(View view){
        super(view.getContext());
        this.view = view;
        final int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
        FrameLayout.LayoutParams params = new LayoutParams(wrapContent,wrapContent);
        this.view.setLayoutParams(params);
        this.view.setClickable(true);
        addView(view);
    }

    public interface RenderDelegate{
        void onDisplay(MapPoint point, View widget);
    }

    public void setRenderDelegate(RenderDelegate renderDelegate){
        this.renderDelegate = renderDelegate;
    }

    public void showAtPoint(MapPoint point){
        if (view == null){
            return;
        }
        point.setWidget(this);
        setPosition(point.getCenter());
        if (renderDelegate != null){
            renderDelegate.onDisplay(point, view);
        }
        view.setVisibility(View.VISIBLE);
    }
    private void setPosition(PointF point){
        float x = point.x;
        float y = point.y;

        setPosition(x, y);
    }

    private void setPosition(float x, float y){
        if (position.equals(x, y) ){
            return;
        }
        position.set(x, y);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
        int left = (int) x;
        int top  = (int) y;

        params.gravity = Gravity.CENTER_VERTICAL | Gravity.TOP;
        params.leftMargin = left;
        params.topMargin  = top;

        view.setLayoutParams(params);
    }



}
